package ext.vpde.cadvaulting.migration;

import java.io.*;
import java.util.*;

public class CreateUserGroups {

	public static void main ( String [] args ) throws Exception {
		if (args.length != 1) {
			System.out.println("\nUsage: java.ext.ncs.CreateUserGroups loadfile");
		} else {			
			writeGroups(getGroups(args[0]));
			writeUsers(getUsers(args[0]));
            writeUserGroups(args[0]);
		}
    }
	
	private static Hashtable getGroups(String inputFile) throws Exception {
		BufferedReader file = LoadUtil.openInputFile(inputFile);
		Hashtable ht = new Hashtable();
		if (file != null) {
			String s = file.readLine();
			while (s!= null && s.length() > 0) {
				StringTokenizer strTok = new StringTokenizer(s,"|");
				String groupName = strTok.nextToken();
				if (!ht.containsKey(groupName)) ht.put(groupName,groupName);
				s = file.readLine();
			}
		}
		return ht;
	}
	
	private static Hashtable getUsers(String inputFile) throws Exception {
		BufferedReader file = LoadUtil.openInputFile(inputFile);
		Hashtable ht = new Hashtable();
		if (file != null) {
			String s = file.readLine();
			while (s!= null && s.length() > 0) {
				StringTokenizer strTok = new StringTokenizer(s,"|");
				strTok.nextToken();
				String user = strTok.nextToken();
				if (!ht.containsKey(user)) ht.put(user,user);
				s = file.readLine();
			}
		}
		return ht;
	}
	
	private static void writeUserGroups(String inputFile) throws Exception {
		BufferedReader file = LoadUtil.openInputFile(inputFile);
		PrintWriter pw      = LoadUtil.openOutputFile("usergroups.xml");
		if (file != null) {
			String s = file.readLine();
			LoadUtil.writeXMLHeader(pw);
			while (s!= null && s.length() > 0) {
				StringTokenizer strTok = new StringTokenizer(s,"|");
				String group = strTok.nextToken();
				String user  = strTok.nextToken();
				pw.println(LoadUtil.createUserGroupXML(group, user));
				s = file.readLine();
			}
			LoadUtil.writeXMLFooter(pw);
		}
	}
	
	private static void writeGroups(Hashtable ht) throws Exception {
        Enumeration enumeration = ht.elements();
        PrintWriter pw = LoadUtil.openOutputFile("groups.xml");
        LoadUtil.writeXMLHeader(pw);
		while (enumeration.hasMoreElements()) {
			String group = enumeration.nextElement().toString();
			pw.println(LoadUtil.createGroupXML(group));
		}
		LoadUtil.writeXMLFooter(pw);
	}
	
	private static void writeUsers(Hashtable ht) throws Exception {
        Enumeration enumeration = ht.elements();
        PrintWriter pw = LoadUtil.openOutputFile("groupusers.xml");
        LoadUtil.writeXMLHeader(pw);
		while (enumeration.hasMoreElements()) {
			String user = enumeration.nextElement().toString();
			pw.println(LoadUtil.createUserXML(user));	
		}
		LoadUtil.writeXMLFooter(pw);
	}
}